package com.hna.face.controller.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hna.face.base.BaseController;
import com.hna.face.model.BfMenu;
import com.hna.face.model.BfUser;
import com.hna.face.service.IBfMenuService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/****
 * 菜单管理
 * 
 * 
 * @author zhulei
 *
 */
@Controller
public class MenuController extends BaseController {
  
	private final static Logger log = LoggerFactory.getLogger(MenuController.class);
	
	@Autowired
	private IBfMenuService menuService;
	
	


	
	@RequestMapping("/menu/index")
	public String index(HttpServletRequest request) {
		System.out.println("***");
		return "pages/menu/index";
	}
	
	@RequestMapping("/menu/add")
	public ModelAndView add(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("pages/menu/add");
		mav.addObject("pid", request.getParameter("pid"));		
		return mav;
	}
	
	
	@RequestMapping("/menu/edit")
	public ModelAndView edit(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("pages/menu/edit");
		BfMenu menu=menuService.selectById(Long.valueOf(request.getParameter("id")));
		modelAndView.addObject("menu",menu);
		return modelAndView;
	}
	
	
	 /**
	   * 菜单树
	   * 
	   * @param
	   * @return
	   * @throws
	   */
	  @RequestMapping(value = {"/rest/menuTree"}, method = RequestMethod.POST)
	  public @ResponseBody List<Map<String, Object>> menuTree(HttpServletRequest request) {

	    List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
	    Subject currentUser = SecurityUtils.getSubject();
	    String username = currentUser.getPrincipal().toString();
	    Map<String, Object> para = new HashMap<String, Object>();
	    para.put("pid", 0);
	    List<BfMenu> treeList = null;
	    if (username.equals("admin")) {
	    	treeList = menuService.selectAdminMenu(para);
	    }else{      
	      para.put("userName", username);
	      treeList = menuService.selectByUserNameAndPid(para);
	    }
	    for (int i = 0; i < treeList.size(); i++) {
	      Map<String, Object> item = new HashMap<String, Object>();
	      item.put("id", treeList.get(i).getId());
	      item.put("text", treeList.get(i).getMenuname());
	      if (treeList.get(i).getMenucode() != null && !treeList.get(i).getMenucode().equals("")) {
	        Map<String, Object> attributes = new HashMap<String, Object>();
	        attributes.put("url", treeList.get(i).getMenucode());
	        item.put("attributes", attributes);
	      }
	      Map<String, Object> chpara = new HashMap<String, Object>();
	      chpara.put("pid", treeList.get(i).getId());
	      List<BfMenu> treeListChildren = null;
	      if (username.equals("admin")) {
	    	  treeListChildren = menuService.selectAdminMenu(para);
	      }else{        
	        chpara.put("userName", username);
	        treeListChildren = menuService.selectByUserNameAndPid(chpara);
	      }
	      if (treeListChildren.size() > 0) {
	        item.put("children", genChildTree(username, treeList.get(i).getId()));
	      }
	      items.add(item);
	    }
	    return items;
	  }
	
	  private List<Map<String, Object>> genChildTree(String username, Long parentId) {
		    List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
		    Map<String, Object> para = new HashMap<String, Object>();
		    para.put("pid", parentId);
		    List<BfMenu> treeList = null;
		    if (username.equals("admin")) {
		    	treeList = menuService.selectAdminMenu(para);
		    }else{      
		      para.put("userName", username);
		      treeList = menuService.selectByUserNameAndPid(para);
		    }
		    for (int i = 0; i < treeList.size(); i++) {
		      Map<String, Object> item = new HashMap<String, Object>();
		      item.put("id", treeList.get(i).getId());
		      item.put("text", treeList.get(i).getMenuname());
		      if (treeList.get(i).getPid() == 0) {
		        item.put("state", "closed");
		      }
		      if (treeList.get(i).getMenucode() != null && !treeList.get(i).getMenucode().equals("")) {
		        Map<String, Object> attributes = new HashMap<String, Object>();
		        attributes.put("url", treeList.get(i).getMenucode());
		        item.put("attributes", attributes);
		      }

		      Map<String, Object> chparams = new HashMap<String, Object>();
		      chparams.put("pid", treeList.get(i).getId());
		      List<BfMenu> treeListChildren =  null;
		      if (username.equals("admin")) {
		    	  treeListChildren= menuService.selectAdminMenu(para);
		      }else{        
		        chparams.put("userName", username);
		        treeListChildren = menuService.selectByUserNameAndPid(chparams);
		      }
		      if (treeListChildren.size() > 0) {
		        item.put("children", genChildTree(username, treeList.get(i).getId()));
		      }
		      items.add(item);
		    }
		    return items;
		  }
	  
	  /**
	   *
	   * 菜单管理列表
	   * 
	   * @param
	   * @return
	   * @throws
	   */
	  @RequestMapping(value = {"/rest/menuList"}, method = RequestMethod.POST)
	  public @ResponseBody Map<String, Object> menuList(HttpServletRequest request,BfMenu menu) {
//		    userDao._test();  
//		    userDao.createCollection();
//	        UserEntity entity1 = new UserEntity();  
//	        entity1.setId("5");  
//	        entity1.setAge(1);  
//	        entity1.setBirth(new Date());  
//	        entity1.setPassword("asdfasdf");  
//	        entity1.setRegionName("北京");  
//	        entity1.setWorks(1);  
//	        userDao.insert(entity1);  
//	        userDao.update(entity1);  
//	        userDao.createCollection();  
//	      
//	        List<UserEntity> list = userDao.findList(0, 10);  
		  
		  Map<String, Object> res = new HashMap<String, Object>();
	    try {
	    	Wrapper<BfMenu> wrapper=new EntityWrapper<BfMenu>();
	    	List<BfMenu> menuList=menuService.selectList(wrapper);
	      // res.put("total", total);
	      res.put("rows", menuList);
	      res.put("success", "true");
	      
	      return res;
	    } catch (Exception e) {
	      res.put("success", "false");
	      return res;
	    }
	  }
	  
	  
	  /**
	   * 新增,修改菜单
	   * 
	   * @param
	   * @return
	   * @throws
	   */
	  @RequestMapping(value = {"/rest/menuAdd"}, method = RequestMethod.POST)
	  public @ResponseBody Map<String, Object> menuAdd(HttpServletRequest request,BfMenu menu) {
	    Map<String, Object> res = new HashMap<String, Object>();
	    try {
	    	BfUser user=(BfUser)request.getSession().getAttribute("userInfo");
	    	menuService.insert(menu);
	      this.saveUserlog(request, "菜单管理："+user.getUsername()+"添加菜单操作");
	      res.put("success", "true");
	      return res;
	    } catch (Exception e) {
	      e.printStackTrace();
	      res.put("success", "false");
	      res.put("msg", e.getMessage());
	      return res;
	    }
	  }
	  
	  /**
	   * 新增,修改菜单
	   * 
	   * @param
	   * @return
	   * @throws
	   */
	  @RequestMapping(value = {"/rest/menuUpdate"}, method = RequestMethod.POST)
	  public @ResponseBody Map<String, Object> menuUpdate(HttpServletRequest request,BfMenu menu) {
	    String saveType = request.getParameter("saveType");// 1：新增 2:修改
	    Map<String, Object> res = new HashMap<String, Object>();
	    try {
	      BfUser user=(BfUser)request.getSession().getAttribute("userInfo");
	      
	      String pid = request.getParameter("pid"); // 父菜单ID
	      if (menu.getPid() != 0) {
	    	  BfMenu m = menuService.selectById(menu.getPid());
	        if (null != m && m.getPid() != 0) {
	          res.put("success", "false");
	          res.put("msg", "最多添加二级菜单");
	          return res;
	        }
	      }
//	      String displayOrderstr = menuService.selectMaxDisplayOrder(pid); // 处理菜单顺序号
//	      int displayOrder = 0;
//	      if (displayOrderstr == null || "".equals(displayOrderstr)) {
//	        displayOrder = 1;
//	      } else {
//	        displayOrder = Integer.parseInt(displayOrderstr) + 1;
//	      }
//	      menu.setDisplayorder(new Integer(displayOrder));
	      if ("1".equals(saveType)) { // 添加
	        menuService.insert(menu);
	        this.saveUserlog(request, "菜单管理："+user.getUsername()+"添加菜单操作");
	      } else {
	        menuService.updateById(menu);
	        this.saveUserlog(request, "菜单管理："+user.getUsername()+"修改菜单操作");
	      }
	      res.put("success", "true");
	      return res;
	    } catch (Exception e) {
	      e.printStackTrace();
	      res.put("success", "false");
	      res.put("msg", e.getMessage());
	      return res;
	    }
	  }
	  
	  
	  /**
	   * 菜单删除
	   * 
	   * @param request
	   * @return
	   */
	  @RequestMapping(value = {"/rest/menuDel"}, method = RequestMethod.POST)
	  public @ResponseBody Map menuDel(HttpServletRequest request,String ids) {
	    Map<String, Object> res = new HashMap<String, Object>();
	    try {
	    	  BfUser user=(BfUser)request.getSession().getAttribute("userInfo");
		      menuService.deleteBatchIds(Arrays.asList(ids.split(",")));
		      this.saveUserlog(request, "菜单管理："+user.getUsername()+"删除菜单操作");
		      res.put("success", "true");
	    } catch (Exception e) {
	      res.put("success", "false");
	      res.put("msg", e.getMessage());
	    }
	    return res;
	  }
	  
}
